package me.zingon.open.bigsmart.thread;

import lombok.extern.slf4j.Slf4j;
import me.zingon.open.bigsmart.model.Job;
import me.zingon.open.bigsmart.queue.DelayJobBucket;
import me.zingon.open.bigsmart.queue.JobPoll;
import me.zingon.open.bigsmart.queue.ReadyQueue;
import me.zingon.open.bigsmart.service.OperationService;
import me.zingon.open.bigsmart.worker.IWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @author ztc 1423047407@qq.com
 * @version 1.0
 * @date 2020-8-6 16:10
 */
@Component
@Slf4j
public class TopicTimer {

    @Autowired
    DelayJobBucket delayJobBucket;

    @Autowired
    ReadyQueue readyQueue;

    @Autowired
    JobPoll jobPoll;

    @Autowired
    OperationService operationService;

    @Async("workerTimerExecutor")
    public void run(String topic, IWorker worker){
        log.info("baseTopicTimer 轮训线程启动:{}",topic);
        for (;;){
            Job job = operationService.getReadyJob(topic);
            if(job == null){
                this.sleep(999);
                continue;
            }
            worker.work(job);
            log.debug("处理job：{}",job);
        }
    }

    private void sleep(long ms){
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            log.error("{}",e);
        }
    }


}
